<template>
  <div>
    <vx-card class="mb-3">
      <template v-slot:header>
        <div class="title">
          <h4>配置详情</h4>
          <div class="btnGroup">
            <vs-button
              color="primary"
              @click="saveConfig"
              size="small"
              class="mr-3"
              icon-pack="feather"
              icon="icon-save"
            >保存</vs-button>
            <vs-button
              color="primary"
              @click="previousPage"
              size="small"
              icon-pack="feather"
              icon="icon-chevron-left"
            >返回</vs-button>
          </div>
        </div>
      </template>
    </vx-card>
    <div class="vx-row">
      <div class="vx-col w-full md:w-1/3">
        <vx-card class="personTreeWrapper">
          <template v-slot:header>
            <div class="title">
              <h4>人员配置</h4>
            </div>
          </template>
          <VuePerfectScrollbar class="mt-5 scroll-area">
            <tree-component
              ref="tree"
              node-key="id"
              :data="treeData"
              :render-content="renderContent"
              :default-expanded-keys="expandedKeys"
              @check="handleNodecheck"
              @node-click="handleNodeClick"
              show-checkbox
            ></tree-component>
          </VuePerfectScrollbar>
        </vx-card>
      </div>
      <div class="vx-col w-full md:w-2/3 userGroupInfo">
        <div class="divtop">
          <vx-card class="pt-3 mb-5 checkedPeople1">
            <h5>角色配置</h5>
            <VuePerfectScrollbar class="mt-3  " id="checkedPeople">
               <el-select v-model="selectedRole"  multiple   placeholder="请选择" class="select_role">
            <el-option
              v-for="roleItem in roleConfigure"
              :key="roleItem.id"
              :label="roleItem.name"
              :value="roleItem.id"
            ></el-option>
          </el-select>
            </VuePerfectScrollbar>
          </vx-card>
          <vx-card class="pt-3 mb-5">
            <h5>视图配置</h5>
            <VuePerfectScrollbar class="mt-3 checkedPeople" >
              <el-select
                v-model="value"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择视图配置"
                clearable
                class="select_view"
              >
                <el-option
                  v-for="item in optionsVivs"
                  :key="item.value"
                  :label="item.viewName"
                  :value="item.userViewId"
                ></el-option>
              </el-select>
            </VuePerfectScrollbar>
          </vx-card>
        </div>
        <vx-card class="pt-3 vx_boxbottom">
           <VuePerfectScrollbar class="mb-4 sitConfig">
         
          <h5 class="mt-5 mb-4">桥梁配置</h5>
         
            <ul class="centerx">
              <li :key="plantV.deptId" v-for="plantV in plantConfigure">
                <vs-checkbox
                disabled
                  v-model="confirmPlantConfigure"
                  :vs-value="plantV.deptId"
                >{{plantV.name}}</vs-checkbox>
              </li>
            </ul>
          </VuePerfectScrollbar>
        </vx-card>
      </div>
    </div>
  </div>
</template>

<script>
import VuePerfectScrollbar from "vue-perfect-scrollbar";
import TreeComponent from "@/components/model-tree/ModelTree.vue";
export default {
  props: ["userGroupId", "usergroupdata", "userGroupConfigure"],
  data() {
    return {
      treeData: [],
      peopleList: [], //已选人员配置
      peopleListKeys: [], //已选人员配置
      roleConfigure: [], //角色配置
      plantConfigure: [], //桥梁配置
      selectedRole: [], //已选角色
      confirmPlantConfigure: [], //已选桥梁
      expandedKeys: [],
      // userViews:[],//用户 
      value: [],
      optionsVivs:[],
      viewId:[],
    };
  },
  methods: {
    setDepDis(value){
      let arr = []
      value.forEach((item,index)=>{
        if(item.type == '4' && !item.children)
        arr.push(index)
      })
      for(let i = arr.length-1;i>=0;i--){
        value.splice(arr[i],1)
      }
      value.forEach((item,index)=>{
        if(item.children && item.children.length)
        this.setDepDis(item.children)
      })
    },
    //获取树
    getTreeData() {
      this.$api.accessControl
        .departmentTree()
        .then(res => {
          this.treeData = res.data.data;
          this.addDisabled(this.treeData)
          this.setDepDis(this.treeData)
          this.treeData[0].children.forEach(zx => {
            this.expandedKeys.push(zx.id);
            if (zx && zx.children) {
              zx.children.forEach(cz => {
                this.expandedKeys.push(cz.id);
              });
            }
          });
          
          this.$nextTick().then(() => {
            const firstNode = document.getElementsByClassName(
              "custom-tree-node"
            );
            for (let i = 3; i < firstNode.length; i++) {
              if (
                firstNode[i].childNodes[0].className ==
                "othericon icon-department"
              ) {
                firstNode[i].click();
              }
            }
          });
          // this.$refs.tree.$refs.tree.setCheckedKeys(this.peopleListKeys);
          // this.treeData[0].children.forEach(zx => {
          // this.expandedKeys.push(zx.id);
          // });
        })
        .catch();
      // setTimeout(() => {
      //   this.$refs.tree.$refs.tree.setCheckedKeys(this.peopleListKeys);
      //   this.treeData[0].children.forEach(zx => {
      //     this.expandedKeys.push(zx.id);
      //   });
      // }, 500);
    },
    addDisabled(data){
      data.forEach(item=>{
        if(item.type != 5)
        item.disabled = true
        if(item.children)
        this.addDisabled(item.children)
      })
    },
    //资源树名称显示
    //树名称显示
    renderContent(h, { node }) {
      let iconSkin;
      if (!node.data.type) {
        iconSkin = "icon-person";
      } else if (node.data.type == 5) {
        iconSkin = "icon-department";
      } else if (node.data.type == 3) {
        iconSkin = "icon-center";
      } else if (node.data.type == 4) {
        iconSkin = "icon-site";
      } else {
        iconSkin = "icon-group";
      }
      return (
        <span class="custom-tree-node flex items-center">
          <i class={`othericon ${iconSkin}`} />
          <span style="margin-left:5px;">{node.data.name}</span>
        </span>
      );
    },
    //资源树-选择,获取选中人员配置树节点
    handleNodecheck() {
      let keys = this.$refs.tree.$refs.tree.getCheckedKeys(true);
      let nodes = this.$refs.tree.$refs.tree.getCheckedNodes(true);
      if(nodes.length==1 && nodes[0].type == 5){
        keys = []
        nodes = []
      }
      let setKeys = new Set(keys);
      let obj = {};
      const newArr = nodes.reduceRight((item, next) => {
        obj[next.id] ? "" : (obj[next.id] = true && item.push(next));
        return item;
      }, []);
      this.peopleListKeys = Array.from(setKeys);
      this.peopleList = newArr;
    },
    handleNodeClick(data, node) {
      console.log(data)
      if (data.type != 5) return;
      this.$api.accessControl
        .getDeptUser(data.id)
        .then(res => {
          if(res.data.data.length==0){
            node.data.disabled = true
          }
          if (!node.data.children) {
            this.$set(node.data, "children", []);
          }
          if(data.children.length==0)
          res.data.data.map(v => {
            data.children.push({
              id: v.userId,
              name: v.realname
            });
          });
           this.$refs.tree.$refs.tree.setCheckedKeys(this.peopleListKeys);
            this.treeData[0].children.forEach(zx => {
              this.expandedKeys.push(zx.id);
            });
          
        })
        .catch();
    },
    // 视图配置
    viewConfiguration() {
      let params = {
        start: 0,
        length: "1000"
      };
      this.$api.accessControl.viewConfiguration(params).then(res => {
        console.log(res.data.data);
        this.optionsVivs = res.data.data
      });
    },
    saveConfig() {
      let params = {
        userGroupId: this.userGroupId,
        deptIds: this.confirmPlantConfigure,
        userIds: this.peopleListKeys,
        roleIds: this.selectedRole,
        viewIds:this.value,
      };
      console.log(params,'1111111111111111111111111111111111111')
      if (params.userIds.length) {
          if (params.roleIds == "") {
            this.$vs.notify({ text: "请选择角色", color: "danger" });
          } else {
            this.$api.accessControl
              .userGroupConfig(params)
              .then(res => {
                // console.log(res,"/////////////////")
                if (res.data.success) {
                  this.peopleList = [];
                  this.confirmPlantConfigure = [];
                  this.selectedRole = [];
                  this.$vs.notify({ text: "保存成功", color: "success" });
                  this.$emit("returnPrev");
                } else {
                  this.$vs.notify({ text: res.data.message, color: "danger" });
                }
              })
              .catch();
          }
       
      } else {
        this.$vs.notify({ text: "请选择用户", color: "danger" });
      }
    },
    //返回用户组表格
    previousPage() {
      this.$emit("returnPrev");
    },
    //删除已选人员
    handleClose(tagId) {
      for (let i = 0; i < this.peopleListKeys.length; i++) {
        if (this.peopleListKeys[i] == tagId) {
          this.peopleListKeys.splice(i, 1);
        }
      }
      this.peopleList = this.peopleList.filter(item => tagId != item.id);
      this.$refs.tree.$refs.tree.setCheckedKeys(this.peopleListKeys, true);
      this.getTreeData();
    }
  },
  components: {
    TreeComponent,
    VuePerfectScrollbar
  },
  created() {
    // this.getTreeData();
    //角色配置
    this.selectedRole = []
    this.$api.accessControl
      .userGroupRole()
      .then(res => {
        this.roleConfigure = res.data.data;
        res.data.data.forEach(item=>{
          this.selectedRole.push(item.id)
        })
        // this.selectedRole = res.data.data[0].id;
      })
      .catch();
    //桥梁配置
    this.$api.accessControl
      .getPlantStation()
      .then(res => {
        // console.log(res,"桥梁")
        this.plantConfigure = res.data.data;
      })
      .catch();
    this.viewConfiguration();
  },
  mounted(){
      // console.log(this.usergroupdata,"00000");
    
  },
  watch: {
    value(newVal){
      let viewArr = []
      newVal.forEach(item=>{
        let i = this.optionsVivs.findIndex(d=>{ return(d.userViewId==item)})
        viewArr.push(this.optionsVivs[i].deptResponses[0].deptId)
        console.log(i)
      })
      this.confirmPlantConfigure = viewArr
    },
    usergroupdata() {
      this.peopleList = [];
      this.peopleListKeys = [];
      let roleIds = []
      if(this.usergroupdata.roles && this.usergroupdata.roles.length)
      this.usergroupdata.roles.forEach(item=>{if(item.roleId) roleIds.push(item.roleId)})
      if (this.usergroupdata.userGroupId) {
        this.usergroupdata.roles && this.usergroupdata.roles.length
          ? (this.selectedRole =roleIds)
          : (this.selectedRole = []);
        if (this.usergroupdata.views && this.usergroupdata.views.length) {
          // this.confirmPlantConfigure = [];
          // this.usergroupdata.depts.forEach(v => {
          //   this.confirmPlantConfigure.push(v.deptId);
          // });
          this.usergroupdata.views.forEach(v => {
            this.confirmPlantConfigure.push(v.deptResponses[0].deptId);
          });
        } else {
          this.confirmPlantConfigure = [];
        }
        if (this.usergroupdata.users && this.usergroupdata.users.length) {
          let selectedPeople = [];
          this.usergroupdata.users.forEach(v => {
            // console.log(v,"羽毛")
            selectedPeople.push({ id: v.userId, name: v.realname });
            this.peopleListKeys.push(v.userId);
          });
          this.peopleList = selectedPeople;
        }
        if(this.usergroupdata.views && this.usergroupdata.views.length){
            let list = [];
            // console.log(this.usergroupdata.views,"bbbbbbb9999")
            this.usergroupdata.views.forEach(item =>{
              // console.log(item.userViewId,"--00===")
              list.push(item.userViewId)
            })
            // console.log(list,"lllleee")
            this.value = list
        }else if(this.usergroupdata.views == null){
          this.value = []
        }
      }
    },
    userGroupConfigure() {
      if (this.userGroupConfigure) {
        console.log(this.userGroupConfigure,"已选桥梁")
        this.getTreeData();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/baseColor.scss";
@import "~@/assets/fonts/other-icon/iconfont.css";
.scroll-area {
  height: calc(var(--vh, 1vh) * 100 - 26rem);
  /deep/ .el-icon-folder-opened:before {
    content: "" !important;
  }
}

/deep/.el-checkbox__input.is-checked .el-checkbox__inner,
/deep/.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: $mainColor;
  border-color: $mainColor;
}
.personTreeWrapper {
  height: calc(100vh - 19rem);
}
.title,
.btnGroup {
  display: flex;
  justify-content: space-between;
  .btnGroup {
    justify-content: flex-end;
  }
}
.checkedPeople {
 height: 255px;
}
.userGroupInfo {
  height: calc(100vh - 19rem);
}
.userGroupInfo .vx-card:nth-child(1) {
  // height: 44%;
  margin-right: 15px;
}
@media (max-width: 1366px) {
  .sitConfig {
    //  height:200px;
    height:30vh
  }
  .checkedPeople {
    height: 255px;
  }
  .userGroupInfo .vx-card {
    overflow: hidden;
  }
}
 .sitConfig {
    //  height:200px;
    height:30vh
  }
h5 {
  font-weight: 600;
}


/deep/ .el-tag .el-tag__close {
  color: #fff;
  background: $mainColor;
}
/deep/.el-tag.el-tag--info{
  color: black;
  background-color: #e9e9eb;
}
.select_view{
  width:100%;
  max-height: 250px;
}
.select_role{
  width:100%;
}
#checkedPeople{
  overflow: hidden;
  border-radius: 5px;
  height:19.5vh
}
.centerx {
  li {
    display: inline-block;
    width: 16rem;
    margin: 4px 10px 12px 16px;
  }
}

.el-select-dropdown__item.selected {
  color: $mainColor;
}

/deep/.el-select .el-input.is-focus .el-input__inner,
/deep/.el-select .el-input__inner:focus,
/deep/.el-select .el-input__inner {
  border-color: $mainColor;
}
/deep/ i.othericon {
  color: $mainColor;
  font-size: 18px;
}
.divtop {
  display: flex;
  height: 47%;
}
.vx_boxbottom{
  height:53%;
}
</style>
